package pe.com.hermes.hermetic.web.controller.general;

import pe.com.hermes.hermetic.beans.MatrizBean;
import pe.com.hermes.hermetic.beans.ClienteBean;
import pe.com.hermes.hermetic.negocio.service.HermeticFacade;
import pe.com.hermes.hermetic.negocio.ultil.Util;
import pe.com.hermes.hermetic.web.controller.base.IController;
import pe.com.hermes.hermetic.web.forms.SelecCuentaForm;
import pe.com.hermes.hermetic.web.forms.SelecClienteForm;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;

import pe.com.hermes.hermetic.negocio.service.TablService;
import pe.com.hermes.hermetic.negocio.ultil.ConstantesHermetic;

@Controller
@RequestMapping("/selecCliente.html") 
@SessionAttributes(value={"listClientes"})

public class SeleccionarClienteController implements IController{
    protected final static Logger logger = Logger.getLogger(SeleccionarClienteController.class);
    @Autowired
    private HermeticFacade servicioHermetic;    
    
    @RequestMapping(method={RequestMethod.GET})  
    protected String showForm(ModelMap model,HttpServletRequest request)throws Exception{
        try {
            logger.info(this.getClass().toString()+" "+"metodo: GET");
            SelecClienteForm form = new SelecClienteForm();
            form.setCliente((String)request.getSession(false).getAttribute("cliente"));
            form.setCodSucuHtb((String)request.getSession(false).getAttribute("sucursal"));
            
            List listClientes = new ArrayList();  
            
            listClientes = servicioHermetic.buscarCliente(form.getCliente(),"", form.getCodSucuHtb());
                    
            //asigno los valores de las cuentas seleccionadas en session
            String[] chksCliente = (String[])request.getSession(false).getAttribute("chksCliente");
            listClientes = Util.setChksSession(chksCliente, listClientes);                
            form.setListClientes(listClientes);
            request.getSession(false).setAttribute("listClientes",listClientes);          
              
            model.put("listClientes",listClientes);
            model.put(FORM_KEY,form);
            return FORM_SELECT_CLIENTE;
        }
        catch (Exception e) {
            logger.error(e);
            return FORM_ERROR_POPUP_VIEW;
        }
    }
  
    @RequestMapping(params={"accion=buscarCliente","desCliente"}) 
    protected String buscarCliente(@RequestParam("desCliente") String desCliente ,ModelMap model,HttpServletRequest request)throws Exception{
                logger.info(this.getClass().toString()+" "+"metodo: GET");
        SelecClienteForm form = new SelecClienteForm();
        form.setCliente((String)request.getSession(false).getAttribute("cliente"));        
        form.setCodSucuHtb((String)request.getSession(false).getAttribute("sucursal"));
        String[] chksCliente = (String[])request.getSession(false).getAttribute("chksCliente");
        //List listSucursales = servicioHermetic.getSucursalesNoTodos();
        List listClientes = new ArrayList();        
        //listModulos = servicioHermetic.getlistModulos(form.getCliente(),codSucuHtb,desMat);
                
        listClientes = servicioHermetic.buscarCliente(form.getCliente(), desCliente, form.getCodSucuHtb());
        listClientes = Util.setChksSession(chksCliente,listClientes);
        //form.setListClientes(listClientes);
        if(desCliente.equals(""))
            request.getSession(false).setAttribute("listClientes",listClientes);
        model.put("listClientes",listClientes);
        model.put(FORM_KEY,form);
        return FORM_SELECT_CLIENTE;
    }
    
    @RequestMapping(params={"accion=searchDesCliente"}) 
    protected @ResponseBody String[] searchDesCliente(HttpServletRequest request)throws Exception{        
        logger.info(this.getClass().toString()+" "+"metodo: searchDesCliente");        
        List listModulos = (List)request.getSession(false).getAttribute("listClientes");
        String[] arrayModulos = new String[listModulos.size()];
        for(int i=0;i<listModulos.size();i++){
            arrayModulos[i] = ((ClienteBean)listModulos.get(i)).getNombre();
        }
        return arrayModulos;
    }
    
    @RequestMapping(params={"accion=selectCodCliente","codCliente"}) 
    protected @ResponseBody String[] selectCodCliente(@RequestParam("codCliente") String codCliente,@ModelAttribute(FORM_KEY) SelecClienteForm form,HttpServletRequest request)throws Exception{        
        logger.info(this.getClass().toString()+" "+"metodo: selectCodCliente");        
        String[] chksCliente = (String[])request.getSession(false).getAttribute("chksCliente");
        if(("").equals(codCliente))
            return chksCliente; 
        if(chksCliente!=null)
            for(int i=0;i<chksCliente.length;i++){                
                if(chksCliente[i]!=null&&chksCliente[i].equals(codCliente)){
                    break;
                }
                if(chksCliente[i]==null){
                    chksCliente[i] = codCliente;
                    break;
                }
            }            
        else{
            chksCliente= new String[1000];
            chksCliente[0]=codCliente;
        }        
        request.getSession(false).setAttribute("chksCliente",chksCliente);        
        return chksCliente;
    }
    
    @RequestMapping(params={"accion=deselectCodCliente","codCliente"}) 
    protected @ResponseBody String[] deselectCodCliente(@RequestParam("codCliente") String codCliente,@ModelAttribute(FORM_KEY) SelecClienteForm form,HttpServletRequest request)throws Exception{        
        logger.info(this.getClass().toString()+" "+"metodo: deselectCodCliente");        
        String[] chksCliente = (String[])request.getSession(false).getAttribute("chksCliente");

        if(chksCliente!=null && chksCliente.length > 0)
            for(int i=0;i<chksCliente.length;i++){                
                if(chksCliente[i]!=null && chksCliente[i].equals(codCliente)){
                    chksCliente[i] = null;
                    break;
                }
            }            
        
        request.getSession(false).setAttribute("chksCliente",chksCliente);        
        return chksCliente;
    }        
    
    @RequestMapping(params={"accion=seleccionarClientes"})
    protected void seleccionarClientes(ModelMap model,@ModelAttribute(FORM_KEY) SelecClienteForm form,HttpServletRequest request)throws Exception{
        logger.info("seleccionarClientes");
        String[] _chk = request.getParameterValues("_chk");
        request.getSession(false).setAttribute("_chk",_chk);
    } 

    @RequestMapping(params={"accion=selectTodos","codTodos"}) 
    protected String selectTodos(@RequestParam("codTodos") boolean codTodos ,ModelMap model,HttpServletRequest request)throws Exception{
        logger.info(this.getClass().toString()+" "+"metodo: GET");
        //SelecClienteForm form = (SelecClienteForm)model.get("form");//new SelecCuentaForm();
         SelecClienteForm form = new SelecClienteForm();
        //Asigno el check a todos los elenmentos de la lista Cuenta        
         
        List listClientes = (List)request.getSession(false).getAttribute("listClientes"); 
        
        listClientes = Util.setChksTodos(codTodos, listClientes);        
            //form.setListClientes(listClientes);
        
        //Subo a session los todos los Checks Cuenta
        if (codTodos) {
            String[] chksCliente = Util.listToStringArray(listClientes);
            request.getSession(false).setAttribute("chksCliente",chksCliente);       
        }else {
            request.getSession(false).setAttribute("chksCliente",null);        
        }
        
        request.getSession(false).setAttribute("listClientes",listClientes);
        model.put("listClientes",listClientes);
        model.put(FORM_KEY,form);
        return FORM_SELECT_CLIENTE;
    }

}
